import os
import logging
import re
import shutil
import subprocess
import time
import sys
import requests
import yaml

import importlib as imp
imp.reload(sys)
# sys.setdefaultencoding('utf8')

HITC_TOOL_PATH = os.path.abspath(os.path.dirname(__file__))
HITC_PATH = os.path.join(HITC_TOOL_PATH, 'hitc')
PUB_HITC_PATH = os.path.join(HITC_TOOL_PATH, 'aidi-cli')
SERVICE_PATH = os.path.dirname(HITC_TOOL_PATH)
BASE_PATH = os.path.dirname(SERVICE_PATH)
sys.path.append(BASE_PATH)
logger = logging.getLogger('log')
DEFAULT_WAIT_EXISTS_TIME_OUT = 30 * 60
DEFAULT_WAIT_EXISTS_INTERVAL = 60
DEFAULT_CONFIG_PATH = os.path.join(HITC_TOOL_PATH, 'config_default.yaml')
CONFIG_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                           'config_default.yaml')


def get_token_from_config(config_path):
    with open(config_path, encoding='utf8') as fin:
        config = yaml.load(fin, Loader=yaml.SafeLoader)
    return config.get('token', '')


DEFAULT_TOKEN = get_token_from_config(CONFIG_PATH)


def cmd(s):
    logger.info(s)
    os.system(s)


def get_file_create_time(path):
    return int(os.path.getctime(path))


def get_current_time():
    return int(time.time())


def time_diff(path):
    if os.path.exists(path):
        return float(get_current_time() - get_file_create_time(path)) / (60 * 60)
    else:
        return False


def find_artifact_data(artifact):
    # 查询项目下的所有artifact
    res_body = requests.get(
        url='http://issue.aidi.hobot.cc/api/v1/artifact/{}/issues?perNum=1000'.format(artifact),
        headers={"Cookie": "user-token={}".format(DEFAULT_TOKEN),
                 "Content-Type": "application/json",
                 "X-Forwarded-User": DEFAULT_TOKEN}).json()
    return res_body['data']['page']['itemList']


def cmd_with_output(c):
    logger.info(c)
    print(c)
    # return None, None, None
    p = subprocess.Popen(
        c, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    if err is not None:
        err = err.decode(errors='replace')
    if out is not None:
        out = out.decode(errors='replace')
    return out, err, p.returncode


def download_aidi(hitc_path, local_path, pack_name):
    tool = HITC_PATH
    config_file = DEFAULT_CONFIG_PATH
    if not os.path.exists(local_path):
        return False
    out, err, code = cmd_with_output(
        '{} bkt-file cp -R  --pattern "{}" "{}" "{}" -C {} --mkdir --continue'.format(tool, pack_name, hitc_path,
                                                                                      local_path, config_file
                                                                                      ))


def for_artifact_download(idx, local_path, start_with=None):
    """
    idx:artifact编号
    Local_path:本地路径
    start_with:需要下载pack前缀； 如['PNC', 'NDMLOC', 'FUSION6V']
    """
    data = find_artifact_data(idx)
    for i in data:
        path = i.get('packPath')
        pack_name = path.split('/')[-1]
        hitc_path = '/'.join(path.split('/')[:-1]) + '/'
        time_in_name = '_'.join(pack_name.split('_')[1:3])
        if start_with:
            for _ in start_with:
                _pack_name = _ + '_' + time_in_name
                download_aidi(hitc_path, local_path, _pack_name)
        else:
            download_aidi(hitc_path, local_path, time_in_name)


if __name__ == '__main__':
    for_artifact_download(idx=2637, local_path='/mnt/data-3/huajiang.liu/BADCASE/Pilot_CICD/', start_with=['PNC', 'NDMLOC', 'FUSION6V'])
